const helper = require('../../xci/helper')
const auth = require('../../xci/auth')
const {email, idcardNumber} = require('../../xci/validator')
Page({
  data: {
    formName: 'loginForm',
    alignType: 'end',
    labelWidth: '160rpx',
    rule: {
      phone: [
        {required: true, message: '请输入注册手机号'},
      ],
      captcha: [
        {required: true, message: '请输入手机验证码'},
        {len: 4, message: '请输入4位验证码'},
      ],
      idcard: [
        {validator: idcardNumber, message: '请输入正确的身份证号码'},
      ],
      name: [
        {required: true, message: '请输入姓名'}
      ],
      email: {validator: email, message: '请输入正确的邮箱地址'}
    },
    userInfo: null,
    phone: '',
    name: ''
  },
  onLoad: function (options) {
    wx.lin.initValidateForm(this)
  },
  onShow() {
    const userInfo = auth.getTokenInfo()
    if (userInfo) {
      this.setData({
        userInfo,
        phone: userInfo.phone || '',
        name: userInfo.name || ''
      })
    }
  },
  onSave() {
    wx.lin.submitForm(this.data.formName)
  },
  async onSubmit(e) {
    console.log(e.detail)
    if (e.detail.isValidate === false) return

    const openid = await auth.getOpenid()
    await auth.register({...e.detail.values, wechatid: openid})
    //页面跳转回首页
    wx.switchTab({url: helper.getHomePagePath()})
  },
  async onGetPhoneNumber(e) {
    if (!e.detail.encryptedData || !e.detail.iv) return
    const result = await auth.getPhoneNumber(e.detail.encryptedData, e.detail.iv)
    this.setData({
      phone: result.phoneNumber
    })
  },
  async onGetNickName() {
    const result = await auth.getUserProfile('需要获取你的微信昵称')
    this.setData({
      name: result.nickName
    })
  },

})